//
//  M_PhotoOneViewController.m
//  Model
//
//  Created by apple on 2018/7/11.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "M_PhotoOneViewController.h"
#import "M_PhotoOneCollectionViewCell.h"
#import "M_PhotoDetailViewController.h"
#import "M_PhotoMineGRViewController.h"
#import <UShareUI/UShareUI.h>

#import "MJRefresh.h"
#import "MJRefreshHeader.h"
#import "MJRefreshFooter.h"

@interface M_PhotoOneViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
{
    UIView *grayView;//
}
@property (nonatomic,strong) UICollectionView *huYuCollectionView;
@property (nonatomic,strong) UIButton *collectionBtn;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, assign) NSInteger page2;
@property (nonatomic, strong) NSMutableArray *qiTaArr;

@end

@implementation M_PhotoOneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creationView];
    
    _page2 = 1;
    // Do any additional setup after loading the view.
}
- (void)zj_viewDidLoadForIndex:(NSInteger)index {
    //    NSLog(@"%@",self.view);
    //    NSLog(@"%@", self.zj_scrollViewController);
    
    
}
- (void)zj_viewWillAppearForIndex:(NSInteger)index {
    // NSLog(@"viewWillAppear------");
    __weak typeof(self) weakself = self;
    [self creationData];
    
    self.huYuCollectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [weakself creationDataJZ];
    }];
    
    self.huYuCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakself creationData];
        
        [self.huYuCollectionView.mj_header beginRefreshing];
    }];
    
    
}
- (void)zj_viewDidAppearForIndex:(NSInteger)index {
    // NSLog(@"viewDidAppear-----");
    
}
- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return  _dataArr;
}
- (NSMutableArray *)qiTaArr{
    if (!_qiTaArr) {
        _qiTaArr = [NSMutableArray array];
        
    }
    return _qiTaArr;
    
}
- (void)creationData{
    
    [self.huYuCollectionView.mj_header endRefreshing];
    
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
//    hud.tag = 500;
//    //提示文本
//    hud.labelText = @"正在加载...";
//    //是否有遮罩
//    hud.dimBackground = YES;
        _page2 = 1;
        NSString *strPage = [NSString stringWithFormat:@"%ld", (long)_page2];
        NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
        
        [productParams setValue:strPage forKey:@"page"];
        
//        [productParams setValue:@"10" forKey:@"pagesize"];
        NSString *type = [NSString stringWithFormat:@"%ld", (long)self.orderStatus];
        [productParams setValue:type forKey:@"type"];
        [[MNetworkHandler sharedInstance]conURL:albumsbytype networkType:NetWorkPOST params:productParams delegate:nil showHUD:NO successBlock:^(id returnData) {
            
            if ([[returnData objectForKey:@"Status"]intValue]==200) {
                
                self.qiTaArr = [returnData objectForKey:@"Data"];
                
                
                NSLog(@"DDDDDDDDDDDD%@", self.qiTaArr);
                
                [self.huYuCollectionView reloadData];
                //
                //
//                [hud removeFromSuperview];
            }
            
            else {
                
                [PublicFunction showAlert:nil message:[returnData objectForKey:@"Msg"] duration:5.0f];
//                [hud removeFromSuperview];
                
            }
            
        } failureBlock:^(NSError *error) {
            
            NSLog(@"%@",error);
            
            [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
            //        [hud removeFromSuperview];
        }];
        
        
//    }
    
    
    
}
- (void)creationDataJZ{
    

    _page2++;


        NSString *strPage = [NSString stringWithFormat:@"%ld", (long)_page2];
        NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
        
        [productParams setValue:strPage forKey:@"page"];
        
//        [productParams setValue:@"10" forKey:@"pagesize"];
        NSString *type = [NSString stringWithFormat:@"%ld", (long)self.orderStatus];
        [productParams setValue:type forKey:@"type"];
        
        [[MNetworkHandler sharedInstance]conURL:albumsbytype networkType:NetWorkPOST params:productParams delegate:nil showHUD:NO successBlock:^(id returnData) {
            
            if ([[returnData objectForKey:@"Status"]intValue]==200) {
                
                NSMutableArray *arr =[returnData objectForKey:@"Data"];
                
                if (arr.count == 0) {
                    
                    [self.huYuCollectionView.mj_footer endRefreshing];
                    
                }else {
                    
                    [self.qiTaArr addObjectsFromArray:arr];
                    
                    NSLog(@"JZJZJZJZJZJJZJZJZJZJZJJZJZ%@", self.qiTaArr);
                    
                    
                }
                //
                //
                [self.huYuCollectionView reloadData];
                [self.huYuCollectionView.mj_footer endRefreshing];
                //
            }
            //
            else {
                //
                
                [PublicFunction showAlert:nil message:[returnData objectForKey:@"Msg"] duration:5.0f];
                [self.huYuCollectionView.mj_footer endRefreshing];
                //
            }
            
        } failureBlock:^(NSError *error) {
            
            NSLog(@"%@",error);
            
            [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
            
        }];
//    }
    
    
}
- (void)creationView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    //    layout.itemSize = CGSizeMake(screenScale(290), screenScale(290));
    //    layout.minimumLineSpacing = screenScale(20);
    //    layout.minimumInteritemSpacing = screenScale(20);
    
    _huYuCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT - 49 - 40 - 64 - (KIsiPhoneX?55:0)) collectionViewLayout:layout];
    _huYuCollectionView.showsVerticalScrollIndicator = NO;
    _huYuCollectionView.delegate = self;
    _huYuCollectionView.dataSource = self;
    _huYuCollectionView.backgroundColor = getColor(@"f7f7f7");

    [_huYuCollectionView registerNib:[UINib nibWithNibName:@"M_PhotoOneCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"M_PhotoOneCollectionViewCell"];
    
    [self.view addSubview:_huYuCollectionView];
    
    
    
    
    
}
#pragma mark -------------------- collectionView ----------------------
//创建头视图
//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
//           viewForSupplementaryElementOfKind:(NSString *)kind
//                                 atIndexPath:(NSIndexPath *)indexPath {
//
//}
#pragma mark --- UICollectionViewDelegate ---
//确定section的个数

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

{
    
    return 1;
    
}
// 设置section头视图的参考大小，与tableheaderview类似
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout
//referenceSizeForHeaderInSection:(NSInteger)section {
//
//}

//设置每个 UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    return CGSizeMake((DEF_SCREEN_WIDTH-36)/2, 245);
    
    
}

//定义每个UICollectionView 的间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    //    if (section == 2) {
    return UIEdgeInsetsMake(12, 12, 12, 12);
    //    }else{
    //        return UIEdgeInsetsMake(0, 0, 0, 0);//上、左、下、右
    //    }
    
}

//定义每个UICollectionView 的横向间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    return 12;
}


-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    

    M_PhotoMineGRViewController *vc = [[M_PhotoMineGRViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    //modelHead
    vc.name = [self.qiTaArr[indexPath.row] objectForKey:@"modelName"];
    vc.modelID = [[self.qiTaArr[indexPath.row] objectForKey:@"modelId"] integerValue];
    vc.headImg = [self.qiTaArr[indexPath.row] objectForKey:@"modelHead"];
    
    [self.navigationController pushViewController:vc animated:YES];
    
    
    
    
}

#pragma mark --- UICollectionViewDataSource ---
//确定每个section对应的item的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
//    if (self.orderStatus == 1000) {
//         return self.dataArr.count;
//    }else{
        return self.qiTaArr.count;
//    }
   
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    M_PhotoOneCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"M_PhotoOneCollectionViewCell" forIndexPath:indexPath];
    cell.shareButton.hidden = YES;
    
//    [cell.shareButton addTarget:self action:@selector(shareClick) forControlEvents:UIControlEventTouchUpInside];
//    if (self.orderStatus == 1000) {
//        NSMutableDictionary *dic = self.dataArr[indexPath.row];
//        cell.nameLab.text = [dic objectForKey:@"name"];
//
//        //    NSString *urlFramePic = manage(AP_HOST, [dic objectForKey:@"pic"]);
//        [cell.headImgView sd_setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"head"]] placeholderImage:[UIImage imageNamed:@""]];
//        [cell.titImgView sd_setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"images"]] placeholderImage:[UIImage imageNamed:@""]];
//    }else{
        NSMutableDictionary *dic = self.qiTaArr[indexPath.row];
        cell.nameLab.text = [dic objectForKey:@"modelName"];
        
        //    NSString *urlFramePic = manage(AP_HOST, [dic objectForKey:@"pic"]);
        [cell.headImgView sd_setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"modelHead"]] placeholderImage:[UIImage imageNamed:@""]];
        [cell.titImgView sd_setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"img"]] placeholderImage:[UIImage imageNamed:@""]];
    
    cell.titImgView.contentMode = UIViewContentModeScaleAspectFill;
    cell.titImgView.clipsToBounds = YES;
    cell.titImgView.userInteractionEnabled = YES;
//    }


    
    return cell;
    
    
    
}
- (void)shareTextToPlatformType:(UMSocialPlatformType)platformType
{
   
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
    NSString* thumbURL =  @"https://mobile.umeng.com/images/pic/home/social/img-1.png";
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"欢迎使用【友盟+】社会化组件U-Share" descr:@"欢迎使用【友盟+】社会化组件U-Share，SDK包最小，集成成本最低，助力您的产品开发、运营与推广！" thumImage:thumbURL];
    //设置网页地址
    shareObject.webpageUrl = @"http://mobile.umeng.com/social";
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
            
//            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先安装微信客户端" preferredStyle:UIAlertControllerStyleAlert];
//            UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
//            [alert addAction:actionConfirm];
//            [self presentViewController:alert animated:YES completion:nil];
//            [self showDetailViewController:alert sender:nil];
            
            
            
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
        
    }];

}



    

- (void)shareClick{
    grayView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
    grayView.backgroundColor = [UIColor colorWithRed:0 / 255.0f green:0 / 255.0f blue:0 / 255.0f alpha:0.2];
    
    [[UIApplication sharedApplication].keyWindow addSubview:grayView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissContactView)];
    [grayView addGestureRecognizer:tapGesture];
    
    
    
    
    
    UIView *changeView = [[UIView alloc] init];
    [grayView addSubview:changeView];
    [changeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.offset(160);
        
    }];
    changeView.backgroundColor = getColor(@"f7f7f7");
    changeView.layer.cornerRadius = 5;
    changeView.layer.masksToBounds = YES;
    ////诶下==微信
    UIButton *weiXinBtn = [[UIButton alloc] init];
    [changeView addSubview:weiXinBtn];
    [weiXinBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(changeView).with.offset(16);
        make.width.offset(50);
        make.height.offset(50);
        make.left.offset((DEF_SCREEN_WIDTH - 150)/4);
    }];
    [weiXinBtn setImage:[UIImage imageNamed:@"icon_wechat_p"] forState:UIControlStateNormal];
    [weiXinBtn addTarget:self action:@selector(weiXinClick) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *weiXinLab = [[UILabel alloc] init];
    [changeView addSubview:weiXinLab];
    [weiXinLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weiXinBtn.mas_bottom).with.offset(5);
        make.centerX.equalTo(weiXinBtn);
        
        
    }];
    weiXinLab.text = @"微信";
    weiXinLab.textColor = getColor(@"818181");
    weiXinLab.font = [UIFont systemFontOfSize:14];
    //
    UIButton *kongJianBtn = [[UIButton alloc] init];
    [changeView addSubview:kongJianBtn];
    [kongJianBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(changeView).with.offset(16);
        make.width.offset(50);
        make.height.offset(50);
        make.left.equalTo(weiXinBtn.mas_right).offset((DEF_SCREEN_WIDTH - 150)/4);
    }];
    [kongJianBtn setImage:[UIImage imageNamed:@"icon_circle"] forState:UIControlStateNormal];
    [kongJianBtn addTarget:self action:@selector(pengYouQuan) forControlEvents:UIControlEventTouchUpInside];
    UILabel *kongJianLab = [[UILabel alloc] init];
    [changeView addSubview:kongJianLab];
    [kongJianLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(kongJianBtn.mas_bottom).with.offset(5);
        make.centerX.equalTo(kongJianBtn);
        
        
    }];
    kongJianLab.text = @"朋友圈";
    kongJianLab.textColor = getColor(@"818181");
    kongJianLab.font = [UIFont systemFontOfSize:14];
    /////
    self.collectionBtn = [[UIButton alloc] init];
    [changeView addSubview:_collectionBtn];
    [_collectionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(changeView).with.offset(16);
        make.width.offset(50);
        make.height.offset(50);
        make.right.equalTo(changeView).offset(-(DEF_SCREEN_WIDTH - 150)/4);
    }];
    [_collectionBtn setImage:[UIImage imageNamed:@"icon_collection-1"] forState:UIControlStateNormal];
    UILabel *collectionLab = [[UILabel alloc] init];
    [changeView addSubview:collectionLab];
    [collectionLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.collectionBtn.mas_bottom).with.offset(5);
        make.centerX.equalTo(self.collectionBtn);
        
        
    }];
    collectionLab.text = @"收藏";
    collectionLab.textColor = getColor(@"818181");
    collectionLab.font = [UIFont systemFontOfSize:14];
    
    
    UIButton *cancelBtn = [[UIButton alloc] init];
    [changeView addSubview:cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.top.equalTo(weiXinBtn.mas_bottom).with.offset(30);
    }];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [cancelBtn setTitleColor:getColor(@"818181") forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(dismissContactView) forControlEvents:UIControlEventTouchUpInside];
    cancelBtn.backgroundColor = [UIColor whiteColor];
    cancelBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    cancelBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 10, 0);
    
}
- (void)dismissContactView {
    [grayView removeFromSuperview];
}
/////////微信
- (void)weiXinClick{
    
    [self shareTextToPlatformType:UMSocialPlatformType_WechatSession];
//    UMSocialPlatformType_WechatTimeLine  UMSocialPlatformType_WechatSession
//    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession)]];
//    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
//        // 根据获取的platformType确定所选平台进行下一步操作}
//
//
//
//    }];

}
- (void)pengYouQuan{
    [self shareTextToPlatformType:UMSocialPlatformType_WechatTimeLine];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
